package com.phonegap.plugins.pgseckey;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;

import org.bouncycastle.openssl.PEMWriter;
import org.json.JSONArray;

import android.content.Context;
import android.os.Environment;

import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;
import com.phonegap.api.PluginResult.Status;

public class PGSeckey extends Plugin {
	private File publicKey;
	private File privateKey;

	@Override
	public PluginResult execute(String action, JSONArray args, String callbackId) {
		File path = Environment.getExternalStoragePublicDirectory("pwmanager");
		if (!path.exists()) {
			path.mkdirs();
		}
		
		this.publicKey = new File(path, "public_key.pem"); 
		this.privateKey = new File(path,"private_key.pem"); 
		
		PluginResult result = null;
		if (action.equals("generateKeys")) {
			try {
				this.generateKeys();
				result = new PluginResult(Status.OK, "Generate Key success");
			} catch (Exception e) {
				result = new PluginResult(PluginResult.Status.ERROR,
						e.getMessage());
			}
		} else if (action.equals("getBase64EncodePrivateKey")) {
			try {
				result = new PluginResult(Status.OK,
						this.getBase64EncodePrivateKey());
			} catch (Exception e) {
				result = new PluginResult(PluginResult.Status.ERROR,
						e.getMessage());
			}
		} else if (action.equals("getBase64EncodePublicKey")) {
			try {
				result = new PluginResult(Status.OK,
						this.getBase64EncodePublicKey());
			} catch (Exception e) {
				result = new PluginResult(PluginResult.Status.ERROR,
						e.getMessage());
			}
		} else if (action.equals("deleteKeys")) {
			result = new PluginResult(Status.OK, this.deleteKeys());
		} else {
			result = new PluginResult(Status.OK, "Error");
		}

		return result;
	}

	public void generateKeys() throws IOException, NoSuchAlgorithmException {
		
		KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
		keyGen.initialize(2048);
		KeyPair pair = keyGen.generateKeyPair();
		PrivateKey priv = pair.getPrivate();
		PublicKey pub = pair.getPublic();

		StringWriter stringWriter = new StringWriter();
		PEMWriter pemFormatWriter = new PEMWriter(stringWriter);
		pemFormatWriter.writeObject(priv);
		pemFormatWriter.close();

		StringBuffer buffer = stringWriter.getBuffer();

		FileOutputStream fosPrivateKey = new FileOutputStream(privateKey);
		fosPrivateKey.write(buffer.toString().getBytes());
		fosPrivateKey.close();

		stringWriter = new StringWriter();
		pemFormatWriter = new PEMWriter(stringWriter);
		pemFormatWriter.writeObject(pub);
		pemFormatWriter.close();

		buffer = stringWriter.getBuffer();

		FileOutputStream fosPublicKey = new FileOutputStream(publicKey);
		fosPublicKey.write(buffer.toString().getBytes());
		fosPublicKey.close();
	}

	public String getBase64EncodePrivateKey() throws IOException,
			NoSuchAlgorithmException, InvalidKeySpecException {
		FileInputStream fis = new FileInputStream(privateKey);

		String result = "";
		int c = 0;
		while ((c = fis.read()) != -1)
			result += String.valueOf((char) c);

		return result;
	}

	public String getBase64EncodePublicKey() throws IOException,
			NoSuchAlgorithmException, InvalidKeySpecException {

		FileInputStream fis = new FileInputStream(publicKey);

		String result = "";
		int c = 0;
		while ((c = fis.read()) != -1)
			result += String.valueOf((char) c);

		return result;
	}

	public String deleteKeys() {
		publicKey.delete();
		privateKey.delete();

		return "Delete Key success";
	}
}
